package com.mojo.concurrent.concurrent_01_thread;

import java.util.concurrent.TimeUnit;

/**
 * 线程的join方法示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2023, 广州九尾信息科技有限公司
 * @date 2023/2/1 20:16
 */
public class Join {
    // public static void main(String[] args) throws InterruptedException {
    //     Thread thread = new Thread(new Domino(Thread.currentThread()));
    //     thread.start();
    //     // 当前主线程需要等待thread线程执行完毕，才能从join()返回
    //     thread.join();
    //     System.out.println("主线程>>>>>>>>>>>>");
    // }
    //
    // static class Domino implements Runnable {
    //     private Thread thread;
    //
    //     public Domino(Thread thread) {
    //         this.thread = thread;
    //     }
    //
    //     @Override
    //     public void run() {
    //         try {
    //             TimeUnit.SECONDS.sleep(2);
    //             System.out.println(">>>>>>线程执行完毕");
    //         } catch (InterruptedException e) {
    //             throw new RuntimeException(e);
    //         }
    //     }
    // }
    public static void main(String[] args) throws Exception {
        Profiler.begin();
        Thread previous = Thread.currentThread();
        for (int i = 0; i < 10; i++) {
            // 每个线程拥有前一个线程的引用，需要等待前一个线程终止，才能从等待中返回
            Thread thread = new Thread(new Domino(previous), String.valueOf(i));
            thread.start();
            previous = thread;
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println(Thread.currentThread().getName() + " terminate.");
        System.out.println("时间间隔毫秒：" + Profiler.interval());
    }

    static class Domino implements Runnable {
        private Thread thread;

        public Domino(Thread thread) {
            this.thread = thread;
        }

        public void run() {
            try {
                thread.join();
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + " terminate.");
        }
    }
}
